
package stratego.java.ssm.online;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * This class is the server class. It is responsible for communicating with the client to get the
 * moves the remote player wants to make and supply outputs to the remote player
 * 
 * @author Sabina Smajlaj
 * @author Mark Aligbe
 */
public class Server
{
	private ServerSocket	socket;
	private Socket	     client;
	private OutputStream	out;
	private InputStream	 in;
	
	public Server(int port)
	{
		try
		{
			// create a server socket on the specified port
			socket = new ServerSocket();
			socket.setReuseAddress(true);
			socket.bind(new InetSocketAddress("0.0.0.0", port));
			client = socket.accept();
			out = client.getOutputStream();
			in = client.getInputStream();
		}
		catch (Exception e)
		{
			try
			{
				if (client != null)
					client.close();
				socket.close();
			}
			catch (IOException e1)
			{
				e1.printStackTrace();
			}
			e.printStackTrace();
		}
	}// end constructor
	
	/**
	 * <code>public boolean connected()</code>
	 * <p>
	 * Returns whether or not this socket is properly connected to the other player.
	 * </p>
	 * 
	 * @return True if both the input and output streams are still open. False otherwise.
	 */
	public boolean connected()
	{
		if (client == null)
			return false;
		if (client.isInputShutdown())
			return false;
		if (client.isOutputShutdown())
			return false;
		return true;
	}
	
	/**
	 * This will close all open connections gracefully
	 */
	public void closeSocket()
	{
		try
		{
			out.close();
			in.close();
			client.close();
			socket.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
	
	/**
	 * <code>public InputStream getSocketInputStream()</code> Returns the InputStream for reading in
	 * messages sent through this half of the socket.
	 * 
	 * @return An InputStream belonging to the Socket enclosed by this class.
	 */
	public InputStream getSocketInputStream()
	{
		return in;
	}
	
	/**
	 * <code>public OutputStream getSocketOutputStream()</code> Returns the OutputStream for sending
	 * messages through this half of the socket.
	 * 
	 * @return An OutputStream belonging to the Socket enclosed by this class.
	 */
	public OutputStream getSocketOutputStream()
	{
		return out;
	}
	
	/**
	 * <code>public Socket getSocket()</code>
	 * <p>
	 * Returns the Socket that is enclosed by this class.
	 * </p>
	 * 
	 * @return The Socket for use with more advanced methods than those provided here.
	 */
	public Socket getSocket()
	{
		return client;
	}
	
}